<?php
/**
 * @author yuanyitian
 * @date 2024/9/26 2:21
 */

namespace api\wechat;

use api\admin\mq;
use utils\wechat_pay;

class order
{
    //重新支付
    public function rePay($data){
        $openid=$data['openid'];
        $order_no=$data['order_no'];
        $total_money=$data['money']*100;
        $res=(new wechat_pay())->get($order_no,$openid,$GLOBALS["wechat_pay_notify"],$total_money);
        return $res;
    }


    //微信支付
    public function pay($data){
        $time=time();
        $type=(int)$data['type'];
        $user_id=(int)$data['user']['user_id'];
        $openid=$data['user']['openid'];
        $name=$data['user']['name'];
        $phone=(int)$data['user']['phone'];
        $address=$data['user']['address'];
        $remark=$data['user']['remark'];
        $total_money=$data['final_price']*100;
        $money=$data['final_price']*100;
        $item=$data['item'];
        $num=(int)$data['num'];
        if(isset($data['pre_time'])){
            $pre_time=$data['pre_time'];
        }else{
            $pre_time='';
        }
//        if(count($item)==0){
//            return out_error('缺少订单明细数据！');
//        }

        $hour=$time-strtotime(date('Y-m-d',$time));
        $con=con();

        mysqli_query($con,"update user set `name`='$name',phone=$phone,address='$address',update_time=$time where id=$user_id");

        $hour=mysqli_query($con,"select * from setting where id in (1,2,3) and value_1<=$hour and value_2>$hour");
        $hour=mysqli_fetch_all($hour,true);

        if(count($hour)==0){
            mysqli_close($con);
            return out_error('缺少时段设置数据！');
        }
        $time_type=(int)$hour[0]['id'];
        $order_no=date('YmdHis').substr($phone,-4).mt_rand(100,999).mt_rand(10,99).mt_rand(1,9);
        $res=mysqli_query($con,"insert into `order`(order_no,user_id,type,time_type,money,create_time,remark,`name`,phone,address,pay_type,pre_time,num) values('$order_no',$user_id,$type,$time_type,$money,$time,'$remark','$name',$phone,'$address',1,'$pre_time',$num)");
        if(!$res){
            mysqli_close($con);
            return out_error('主订单生成失败！');
        }
        $order_id=mysqli_insert_id($con);
        for($i=0;$i<count($item);$i++){
            $goods_id=(int)$item[$i]['id'];
            $num=(int)$item[$i]['num'];
            $money=$item[$i]['money']*100;
            $price=$money/$num;
            $specs_info=$item[$i]['specs_text'];
            mysqli_query($con,"insert into order_item(order_id,goods_id,price,num,money,specs_info,create_time) values($order_id,$goods_id,$price,$num,$money,'$specs_info',$time)");
        }
        mysqli_close($con);

        return (new wechat_pay())->get($order_no,$openid,$GLOBALS["wechat_pay_notify"],(int)$total_money);

    }

    //余额支付
    public function payMoney($data){
        $time=time();
        $type=(int)$data['type'];
        $user_id=(int)$data['user']['user_id'];
        $openid=$data['user']['openid'];
        $name=$data['user']['name'];
        $phone=(int)$data['user']['phone'];
        $address=$data['user']['address'];
        $remark=$data['user']['remark'];
        $money=$data['final_price']*100;
        $item=$data['item'];
        $num=(int)$data['num'];
        if(isset($data['pre_time'])){
            $pre_time=$data['pre_time'];
        }else{
            $pre_time='';
        }
//        if(count($item)==0){
//            return out_error('缺少订单明细数据！');
//        }

        $hour=$time-strtotime(date('Y-m-d',$time));
        $con=con();


        $hour=mysqli_query($con,"select * from setting where id in (1,2,3) and value_1<=$hour and value_2>$hour");
        $hour=mysqli_fetch_all($hour,true);

        if(count($hour)==0){
            mysqli_close($con);
            return out_error('缺少时段设置数据！');
        }
        $time_type=(int)$hour[0]['id'];
        $order_no=date('YmdHis').substr($phone,-4).mt_rand(100,999).mt_rand(10,99).mt_rand(1,9);
        $res=mysqli_query($con,"insert into `order`(order_no,user_id,type,time_type,money,create_time,remark,`name`,phone,address,pay_type,status,pre_time,num) values('$order_no',$user_id,$type,$time_type,$money,$time,'$remark','$name',$phone,'$address',0,1,'$pre_time',$num)");
        if(!$res){
            mysqli_close($con);
            return out_error('主订单生成失败！');
        }

        $order_id=mysqli_insert_id($con);


        mysqli_query($con,"update user set `name`='$name',phone=$phone,address='$address',update_time=$time,money=money-$money where id=$user_id");


        for($i=0;$i<count($item);$i++){
            $goods_id=(int)$item[$i]['id'];
            $num=(int)$item[$i]['num'];
            $money=$item[$i]['money']*100;
            $price=$money/$num;
            $specs_info=$item[$i]['specs_text'];
            mysqli_query($con,"insert into order_item(order_id,goods_id,price,num,money,specs_info,create_time) values($order_id,$goods_id,$price,$num,$money,'$specs_info',$time)");
        }
        mysqli_close($con);

        //打印结账单
        $res=(new mq())->printOrder($order_id);

        return out_right('下单成功！');
    }

    //获取分页列表
    public function getList($data){
        $page=(int)$data['page'];
        $size=(int)$data['size'];
        $start=($page-1)*$size;
        $status=(int)$data['status'];//100代表全部
        $name=$data['name'];
        $phone=(int)$data['phone'];
        $start_time=(int)$data['start_time'];
        $end_time=(int)$data['end_time'];

        if($status===100){
            $status='-2,-1,0,1';
        }
        $where=" where status in ($status)";
        if(!empty($name)){
            $where.=" and name like '%$name%' ";
        }
        if(!empty($phone)){
            $where.=" and phone=$phone";
        }
        if($start_time!=0){
            $where.=" and create_time between $start_time and $end_time";
        }
        $limit=" order by create_time DESC limit $start,$size";
        $sql="select * from `order` ".$where;

        $con=con();
        $time=time();
        $data=mysqli_query($con,$sql.$limit);
        $data=mysqli_fetch_all($data,true);
        $total=mysqli_query($con,$sql);
        $total=mysqli_num_rows($total);

        if(count($data)!=0){
            $order_ids=implode(',',array_column($data,'id'));
            $info=mysqli_query($con,"select a.*,b.name,b.img_url from order_item a left join goods b on (a.goods_id=b.id) where a.order_id in (".$order_ids.")");
            $info=mysqli_fetch_all($info,true);
            for($i=0;$i<count($data);$i++){
                $data[$i]['pre_time_0']=0;
                $data[$i]['pre_time']='00:00';
                switch ($data[$i]['status']){
                    case -2://已退款
                        $data[$i]['status_text']='已退款';
                        break;
                    case -1://已取消
                        $data[$i]['status_text']='已取消';
                        break;
                    case 1://支付成功
                        $data[$i]['status_text']='支付成功';
                        break;
                    case 0://待支付
                        $data[$i]['status_text']='待支付';

                        $d=$time-$data[$i]['create_time'];
                        if($d>0&&$d<=180){
                            $d=180-$d;
                            $data[$i]['pre_time_0']=$d*1000;
                            $data[$i]['pre_time']=date('i:s',$d);
                        }

                        break;
                    default:
                        $data[$i]['status_text']='未知状态';
                        break;
                }
                switch ($data[$i]['type']){
                    case 0:
                        $data[$i]['type_text']='堂食';
                        $data[$i]['type_tiny_text']='堂';
                        break;
                    case 1:
                        $data[$i]['type_text']='配送';
                        $data[$i]['type_tiny_text']='送';
                        break;
                    case 2:
                        $data[$i]['type_text']='预定';
                        $data[$i]['type_tiny_text']='定';
                        break;
                    default:
                        $data[$i]['type_text']='未知类型';
                        $data[$i]['type_tiny_text']='未';
                        break;
                }
                switch ($data[$i]['time_type']){
                    case 0:
                        $data[$i]['time_type_text']='未定义';
                        $data[$i]['time_type_tiny_text']='未';
                        break;
                    case 1:
                        $data[$i]['time_type_text']='早餐';
                        $data[$i]['time_type_tiny_text']='早';
                        break;
                    case 2:
                        $data[$i]['time_type_text']='午餐';
                        $data[$i]['time_type_tiny_text']='午';
                        break;
                    case 3:
                        $data[$i]['time_type_text']='晚餐';
                        $data[$i]['time_type_tiny_text']='晚';
                        break;
                    default:
                        $data[$i]['time_type_text']='未知类型';
                        $data[$i]['time_type_tiny_text']='未';
                        break;
                }
                switch ($data[$i]['pay_type']){
                    case 0:
                        $data[$i]['pay_type_text']='余额支付';
                        $data[$i]['pay_type_tiny_text']='余';
                        break;
                    case 1:
                        $data[$i]['pay_type_text']='微信支付';
                        $data[$i]['pay_type_tiny_text']='微';
                        break;
                    default:
                        $data[$i]['pay_type_text']='未知支付';
                        $data[$i]['pay_type_tiny_text']='未';
                        break;
                }
                $data[$i]['item']=[];
                $data[$i]['money']=sprintf('%.2f',$data[$i]['money']/100);
                if(empty($data[$i]['create_time'])){//订单创建时间
                    $data[$i]['create_time']='';
                }else{
                    $data[$i]['create_time']=date('Y-m-d H:i:s',$data[$i]['create_time']);
                }
                if(empty($data[$i]['update_time'])){//订单修改时间
                    $data[$i]['update_time']='';
                }else{
                    $data[$i]['update_time']=date('Y-m-d H:i:s',$data[$i]['update_time']);
                }
                if(empty($data[$i]['pay_time'])){//订单支付时间
                    $data[$i]['pay_time']='';
                }else{
                    $data[$i]['pay_time']=date('Y-m-d H:i:s',$data[$i]['pay_time']);
                }
                if(empty($data[$i]['accept_time'])){//骑手接单时间
                    $data[$i]['accept_time']='';
                }else{
                    $data[$i]['accept_time']=date('Y-m-d H:i:s',$data[$i]['accept_time']);
                }
                if(empty($data[$i]['send_time'])){//骑手送达时间
                    $data[$i]['send_time']='';
                }else{
                    $data[$i]['send_time']=date('Y-m-d H:i:s',$data[$i]['send_time']);
                }
                if(empty($data[$i]['send_name'])){//骑手名字
                    $data[$i]['send_name']='';
                }
                if(empty($data[$i]['send_phone'])){//骑手手机号
                    $data[$i]['send_phone']='';
                }
                for($o=0;$o<count($info);$o++){
                    if($data[$i]['id']==$info[$o]['order_id']){
                        $info[$o]['price']=sprintf('%.2f',$info[$o]['price']/100);
                        $info[$o]['money']=sprintf('%.2f',$info[$o]['money']/100);
                        if(!empty($info[$o]['img_url'])){
                            $info[$o]['img_url']=explode(',',$info[$o]['img_url']);
                        }
                        $data[$i]['item'][]=$info[$o];
                    }
                }
            }
        }

        mysqli_close($con);
        return out_right([
            'data'=>$data,
            'page'=>$page,
            'size'=>$size,
            'total'=>$total,
            'total_page'=>ceil($total/$size)
        ]);
    }

    //获取配送订单
    public function getListForSearch($data){
        $name=$data['name'];//联系人
        $phone=$data['phone'];//手机号
        $order_no=$data['order_no'];//订单号
        $type=$data['type'];//订单类型（0：堂食，1：配送，2：预定）
        $time_type=$data['time_type'];//餐类型（0：未定义，1：早餐，2：午餐，3：晚餐）
        $send_user_id=$data['send_user_id'];//配送员用户id
        $send_type=(int)$data['send_type'];//配送类型（-1：全部，0：待接单，1：待配送，2：已配送）
        $pay_type=$data['pay_type'];//支付方式（0：余额支付，1：微信支付）
        $status=$data['status'];//状态（-2：已退款，-1：已取消，0：待支付，1：已支付）
        $page=(int)$data['page'];//页码
        $size=(int)$data['size'];//尺寸
        $range_time=(int)$data['range_time'];//时间类型（-1：全部，1：支付时间，2：订单创建时间，3：接单时间，4：：配送时间，5：取消时间，6：退款时间）
        $start_time=(int)$data['start_time'];//开始时间
        $end_time=(int)$data['end_time'];//结束时间

        $start=($page-1)*$size;
        $where=" where is_delete=1 ";
        if(!empty($name)){//联系人
            $where.=" and name like '%$name%'";
        }
        if(!empty($phone)){//联系电话
            $where.=" and phone like '%$phone%'";
        }
        if(!empty($order_no)){//订单号
            $where.=" and order_no like '%$order_no%'";
        }
        if(!empty($type)){//订单类型（0：堂食，1：配送，2：预定）
            $type=implode(',',$type);
            $where.=" and type in ($type)";
        }
        if(!empty($time_type)){//餐类型（0：未定义，1：早餐，2：午餐，3：晚餐）
            $time_type=implode(',',$time_type);
            $where.=" and time_type in ($time_type)";
        }
        if(!empty($pay_type)){//支付方式（0：余额支付，1：微信支付）
            $pay_type=implode(',',$pay_type);
            $where.=" and pay_type in ($pay_type)";
        }
        if(!empty($status)){//状态（-2：已退款，-1：已取消，0：待支付，1：已支付）
            $status=implode(',',$status);
            $where.=" and status in ($status)";
        }
        if(!empty($send_user_id)){//配送员用户id
            $send_user_id=implode(',',$send_user_id);
            $where.=" and send_user_id in ($send_user_id)";
        }
        switch ($send_type){//配送类型（-1：全部，0：待接单，1：待配送，2：已配送）
            case -1://全部
                break;
            case 0://待接单
                $where.=" and accept_time is null";
                break;
            case 1://待配送
                $where.=" and accept_time is not null and send_time is null";
                break;
            case 2://已配送
                $where.=" and accept_time is not null and send_time is not null";
                break;
            default:
                break;
        }

        if($start_time!=0&&$end_time!=0){
            switch ($range_time){//时间类型（-1：全部，1：支付时间，2：订单创建时间，3：接单时间，4：：配送时间，5：取消时间，6：退款时间）
                case -1://全部
                    break;
                case 1://支付时间
                    $where.=" and pay_time between ($start_time and $end_time)";
                    break;
                case 2://订单创建时间
                    $where.=" and create_time between ($start_time and $end_time)";
                    break;
                case 3://接单时间
                    $where.=" and accept_time between ($start_time and $end_time)";
                    break;
                case 4://配送时间
                    $where.=" and send_time between ($start_time and $end_time)";
                    break;
                case 5://取消时间
                    $where.=" and cancel_time between ($start_time and $end_time)";
                    break;
                case 6://退款时间
                    $where.=" and refund_time between ($start_time and $end_time)";
                    break;
                default:
                    break;
            }
        }

        $limit=" order by create_time DESC limit $start,$size";
        $sql="select * from `order` ".$where;

        $con=con();
        $data=mysqli_query($con,$sql.$limit);
        $data=mysqli_fetch_all($data,true);
        $total=mysqli_query($con,$sql);
        $total=mysqli_num_rows($total);

        if(count($data)!=0){
            $order_ids=implode(',',array_column($data,'id'));
            $info=mysqli_query($con,"select a.*,b.name,b.img_url from order_item a left join goods b on (a.goods_id=b.id) where a.order_id in (".$order_ids.")");
            $info=mysqli_fetch_all($info,true);
            for($i=0;$i<count($data);$i++){
                switch ($data[$i]['status']){
                    case -2://已退款
                        $data[$i]['status_text']='已退款';
                        break;
                    case -1://已取消
                        $data[$i]['status_text']='已取消';
                        break;
                    case 1://支付成功
                        $data[$i]['status_text']='支付成功';
                        break;
                    case 0://待支付
                        $data[$i]['status_text']='待支付';
                        break;
                    default:
                        $data[$i]['status_text']='未知状态';
                        break;
                }
                switch ($data[$i]['type']){
                    case 0:
                        $data[$i]['type_text']='堂食';
                        $data[$i]['type_tiny_text']='堂';
                        break;
                    case 1:
                        $data[$i]['type_text']='配送';
                        $data[$i]['type_tiny_text']='送';
                        break;
                    case 2:
                        $data[$i]['type_text']='预定';
                        $data[$i]['type_tiny_text']='定';
                        break;
                    default:
                        $data[$i]['type_text']='未知类型';
                        $data[$i]['type_tiny_text']='未';
                        break;
                }
                switch ($data[$i]['time_type']){
                    case 0:
                        $data[$i]['time_type_text']='未定义';
                        $data[$i]['time_type_tiny_text']='未';
                        break;
                    case 1:
                        $data[$i]['time_type_text']='早餐';
                        $data[$i]['time_type_tiny_text']='早';
                        break;
                    case 2:
                        $data[$i]['time_type_text']='午餐';
                        $data[$i]['time_type_tiny_text']='午';
                        break;
                    case 3:
                        $data[$i]['time_type_text']='晚餐';
                        $data[$i]['time_type_tiny_text']='晚';
                        break;
                    default:
                        $data[$i]['time_type_text']='未知类型';
                        $data[$i]['time_type_tiny_text']='未';
                        break;
                }
                switch ($data[$i]['pay_type']){
                    case 0:
                        $data[$i]['pay_type_text']='余额支付';
                        $data[$i]['pay_type_tiny_text']='余';
                        break;
                    case 1:
                        $data[$i]['pay_type_text']='微信支付';
                        $data[$i]['pay_type_tiny_text']='微';
                        break;
                    default:
                        $data[$i]['pay_type_text']='未知支付';
                        $data[$i]['pay_type_tiny_text']='未';
                        break;
                }
                $data[$i]['item']=[];
                $data[$i]['money']=sprintf('%.2f',$data[$i]['money']/100);
                if(empty($data[$i]['create_time'])){//订单创建时间
                    $data[$i]['create_time']='';
                }else{
                    $data[$i]['create_time']=date('Y-m-d H:i:s',$data[$i]['create_time']);
                }
                if(empty($data[$i]['update_time'])){//订单修改时间
                    $data[$i]['update_time']='';
                }else{
                    $data[$i]['update_time']=date('Y-m-d H:i:s',$data[$i]['update_time']);
                }
                if(empty($data[$i]['pay_time'])){//订单支付时间
                    $data[$i]['pay_time']='';
                }else{
                    $data[$i]['pay_time']=date('Y-m-d H:i:s',$data[$i]['pay_time']);
                }
                if(empty($data[$i]['accept_time'])){//骑手接单时间
                    $data[$i]['accept_time']='';
                }else{
                    $data[$i]['accept_time']=date('Y-m-d H:i:s',$data[$i]['accept_time']);
                }
                if(empty($data[$i]['send_time'])){//骑手送达时间
                    $data[$i]['send_time']='';
                }else{
                    $data[$i]['send_time']=date('Y-m-d H:i:s',$data[$i]['send_time']);
                }
                if(empty($data[$i]['send_name'])){//骑手名字
                    $data[$i]['send_name']='';
                }
                if(empty($data[$i]['send_phone'])){//骑手手机号
                    $data[$i]['send_phone']='';
                }
                for($o=0;$o<count($info);$o++){
                    if($data[$i]['id']==$info[$o]['order_id']){
                        $info[$o]['price']=sprintf('%.2f',$info[$o]['price']/100);
                        $info[$o]['money']=sprintf('%.2f',$info[$o]['money']/100);
                        if(!empty($info[$o]['img_url'])){
                            $info[$o]['img_url']=explode(',',$info[$o]['img_url']);
                        }
                        $data[$i]['item'][]=$info[$o];
                    }
                }
            }
        }

        mysqli_close($con);
        return out_right([
            'data'=>$data,
            'page'=>$page,
            'size'=>$size,
            'total'=>$total,
            'total_page'=>ceil($total/$size)
        ]);
    }

    //配送---接单
    public function getOrder($data){
        $id=(int)$data['id'];
        $user_id=(int)$data['user_id'];

        $con=con();
        $time=time();

        $check=mysqli_query($con,"select * from user_power_config where user_id=$user_id and type=1 and is_delete=1 and status=1 and check_status=1");
        $check=mysqli_num_rows($check);
        if($check===0){
            mysqli_close($con);
            return out_error('无权操作！');
        }
        $user=mysqli_query($con,"select * from user where id=$user_id");
        $user=mysqli_fetch_all($user,true);
        if(count($user)==0){
            mysqli_close($con);
            return out_error('用户非法！');
        }
        $name=$user[0]['name'];
        $phone=(int)$user[0]['phone'];

        $res=mysqli_query($con,"update `order` set send_user_id=$user_id,update_time=$time,accept_time=$time,send_name='$name',send_phone=$phone where id=$id and send_user_id is null");
        mysqli_close($con);
        if($res){
            return out_right();
        }else{
            return out_error('接单失败！');
        }

    }

    //配送---完成
    public function finishOrder($data){
        $id=(int)$data['id'];
        $user_id=(int)$data['user_id'];

        $con=con();
        $time=time();

        $check=mysqli_query($con,"select * from user_power_config where user_id=$user_id and type=1 and is_delete=1 and status=1 and check_status=1");
        $check=mysqli_num_rows($check);
        if($check===0){
            mysqli_close($con);
            return out_error('无权操作！');
        }

        $res=mysqli_query($con,"update `order` set send_time=$time,update_time=$time where id=$id and send_time is null");
        mysqli_close($con);
        if($res){
            return out_right();
        }else{
            return out_error('完成失败！');
        }

    }

    //取消订单
    public function cancelOrder($data){
        $con=con();
        $order_no=$data['order_no'];
        $time=time();

        $res=mysqli_query($con,"update `order` set status=-1,update_time=$time,cancel_time=$time where order_no='$order_no'");
        mysqli_close($con);
        if($res){
            return out_right('取消成功！');
        }else{
            return out_error('取消失败或已取消！');
        }
    }

}